//
//  MDCreateCmdViewController.m
//  MideaWorld_Zizhu
//
//  Created by Minus on 5/25/15.
//  Copyright (c) 2015 Minus. All rights reserved.
//

#import "MDCreateCmdViewController.h"
#import "MDXPGApplianceApi.h"
#import "MDUserDefaults.h"

#import "IDataBodyDevStauts.h"
#import "DeviceStatus.h"
#import "FactoryDataBody.h"
#import "DataBodyDevOld.h"

@interface MDCreateCmdViewController ()
{
    DeviceStatus *_status;
    AirConditionerFuncs *_funcs;
    
    IOSByteArray *_order;
}

@property (weak, nonatomic) IBOutlet UITextField *textFieldProtocol;
@property (weak, nonatomic) IBOutlet UITextField *textFieldTemperature;
@property (weak, nonatomic) IBOutlet UITextField *textFieldTimeOff;
@property (weak, nonatomic) IBOutlet UITextField *textFieldTimeOn;

@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedMode;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedSpeed;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedTempUnit;

@property (weak, nonatomic) IBOutlet UISwitch *switchPower;
@property (weak, nonatomic) IBOutlet UISwitch *switchECO;
@property (weak, nonatomic) IBOutlet UISwitch *switchStrong;
@property (weak, nonatomic) IBOutlet UISwitch *switchUpDown;
@property (weak, nonatomic) IBOutlet UISwitch *switchLeftRight;
@property (weak, nonatomic) IBOutlet UISwitch *switchCleanFan;
@property (weak, nonatomic) IBOutlet UISwitch *switch8Hot;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *labelResult;

@end

@implementation MDCreateCmdViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 开机测试命令
    Byte tempOrder[] = {(Byte)0xAA, (Byte)0x20, (Byte)0xAC, (Byte)0x00, (Byte)0x00, (Byte)0x00, (Byte)0x00, (Byte)0x00 , (Byte)0x01 , (Byte)0x02 , (Byte)0x40 , (Byte)0x43 , (Byte)0x2A , (Byte)0xE6 , (Byte)0x7F, (Byte)0x7F , (Byte)0x00 , (Byte)0x3F , (Byte)0x00 , (Byte)0x00 , (Byte)0x00 , (Byte)0x10 , (Byte)0x02, (Byte)0x00 , (Byte)0x00 , (Byte)0x00 , (Byte)0x00 , (Byte)0x0A , (Byte)0x00 , (Byte)0x00 , (Byte)0x01 , (Byte)0xD9 , (Byte)0x6B };
    
    // 初始化数组
    _order = [IOSByteArray arrayWithLength:sizeof(tempOrder)];
    
    // 构建数组
    for (int i = 0; i < sizeof(tempOrder); i++)
    {
        *IOSByteArray_GetRef(_order, i) = tempOrder[i];
    }
    
    // 初始化设备状态DeviceStatus
    _status = [[DeviceStatus alloc] init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidAppear:(BOOL)animated
{
    
}

// 数据透传
- (void)sendCommand
{
    // 获取设备ID
    NSString *applianceID = [MDUserDefaults sharedInstance].currentApplianceID;
    
    // 数据透传
    [[MDXPGApplianceApi getInstance] transparentCmd:applianceID order:_order completion:^(BaseMessage *baseMessage, NSString *reply, DeviceStatus *status) {
        
        if ([baseMessage getCode] == 0)
        {
            NSLog(@"透传成功，reply: %@", reply);
            NSLog(@"设备状态: %@", status);
            self.labelResult.text = [NSString stringWithFormat:@"透传成功，reply: %@ \n设备状态: %@", reply, status];
            
            [self updateUIWithStatus:status];
        }
        else
        {
            NSLog(@"透传失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]);
            self.labelResult.text = [NSString stringWithFormat:@"透传失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

- (IBAction)actionCreateCommand:(id)sender
{
    // 创建命令
    
//    _status = [[DeviceStatus alloc] init];
    
    // 协议
    SignedByte protocol = 0x03;     // 固定协议号
    if ([self.textFieldProtocol.text length] > 0)
    {
        protocol = (SignedByte)[self.textFieldProtocol.text intValue];
    }
    
    jbyte powerOn = IDataBody_get_POWER_ON();      // 电源开
    jbyte powerOff = IDataBody_get_POWER_OFF();    // 电源关
    
    // 电源开关
    _status->powerStatus_ = self.switchPower.on ? powerOn : powerOff;
    
    // 模式
    SignedByte modes[] = {IDataBodyDevStauts_get_MODE_AUTO(),       // 自动
                            IDataBodyDevStauts_get_MODE_COLD(),     // 制冷
                            IDataBodyDevStauts_get_MODE_DRY(),      // 抽湿
                            IDataBodyDevStauts_get_MODE_HEAT(),     // 制热
                            IDataBodyDevStauts_get_MODE_WIND()};    // 送风
    
    _status->mode_ = modes[self.segmentedMode.selectedSegmentIndex];
    
    // 风速
    SignedByte speeds[] = {IDataBodyDevStauts_get_WIND_SPEED_MUTE(),    // 静音
                            IDataBodyDevStauts_get_WIND_SPEED_LOW(),    // 低风
                            IDataBodyDevStauts_get_WIND_SPEED_MIDDLE(), // 中风
                            IDataBodyDevStauts_get_WIND_SPEED_HIGH(),   // 高风
                            IDataBodyDevStauts_get_WIND_SPEED_FIXED(),  // 固定风
                            IDataBodyDevStauts_get_WIND_SPEED_AUTO()};  // 自动风
    
    _status->fanSpeed_ = speeds[self.segmentedSpeed.selectedSegmentIndex];
    
    // 设置温度
    _status->setTemperature_ = [self.textFieldTemperature.text intValue];
    if (_status->setTemperature_ < 0)
    {
        _status->setTemperature_ = 17;
    }
    
    // 定时关-时
    int hour_off = [self.textFieldTimeOff.text intValue] / 60;
    // 定时关-分
    int minute_off = [self.textFieldTimeOff.text intValue] % 60;
    
    if (hour_off == 0 && minute_off == 0)
    {
        // 不启用 定时关 功能
        _status->timer_off_ = 0;
    }
    else
    {
        // 开启 定时关 功能
        _status->timer_off_ = 1;
        // 设置定时关-时
        _status->timer_off_hour_ = (SignedByte)hour_off;
        // 设置定时关-分
        _status->timer_off_min_ = (SignedByte)minute_off;
    }
    
    // 定时开-时
    int hour_on = [self.textFieldTimeOn.text intValue] / 60;
    // 定时开-分
    int minute_on = [self.textFieldTimeOn.text intValue] % 60;
    
    if (hour_on == 0 && minute_on == 0)
    {
        // 不启用 定时开 功能
        _status->timer_on_ = 0;
    }
    else
    {
        // 开启 定时开 功能
        _status->timer_on_ = 1;
        // 设置定时开-时
        _status->timer_on_hour_ = (SignedByte)hour_on;
        // 设置定时开-分
        _status->timer_on_min_ = (SignedByte)minute_on;
    }
    
    // 特殊功能
    // ECO
    _status->eco_ = self.switchECO.on ? 0x01 : 0x00;
    // 强劲
    _status->tubro_ = self.switchStrong.on ? 0x01 : 0x00;
    // 上下风
    _status->updownFan_ = self.switchUpDown.on ? 0x01 : 0x00;
    // 左右风
    _status->leftRightFan_ = self.switchLeftRight.on ? 0x01 : 0x00;
    
    // 温度单位：1-摄氏度
    SignedByte units[] = {IDataBodyDevStauts_get_TEMPERATURE_Celsius(), IDataBodyDevStauts_get_TEMPERATURE_Fahrenheit()};
    _status->tempUnit_ = units[self.segmentedTempUnit.selectedSegmentIndex];
    
    // 滤网清零
    _status->cleanFanTime_ = self.switchCleanFan.on ? 0x01 : 0x00;
    
    // 8度制热
    _status->Eight_Hot_ = self.switch8Hot.on ? 0x01 : 0x00;
    
    /**
     *  固定的几个步骤，用来生成控制命令
     */
    FactoryDataBody *old = [FactoryDataBody createFactoryDataBodyWithInt:0x40];
    [old updateProtocolWithByte:protocol];
    [old setDataBodyStatusWithBaseDevice:_status];
    _order = [((DataBodyDevOld *)old) toBytesWithBoolean:YES];
    _order = [((DataBodyDevOld *)old) toBytes];
    NSLog(@"---->>> %@", _order);
    self.labelResult.text = [_order description];
    
    // 发送命令
    self.labelResult.text = @"正在发送命令...";
    [self sendCommand];
}

// 查询设备状态
- (IBAction)actionQueryDeviceStatus:(id)sender
{
    // 发送命令
    self.labelResult.text = @"正在查询设备状态...";
    
    ApplianceInfo *currentDevice = [MDUserDefaults sharedInstance].currentAppliance;
    
    [[MDXPGApplianceApi getInstance] queryDeviceInfo:currentDevice completion:^(BaseMessage *baseMessage, DeviceStatus *status, AirConditionerFuncs *funcs) {
        
        NSLog(@"------ Minus 1 device type: %@", @([funcs getDeviceType]));
        
        [[MDXPGApplianceApi getInstance] setFunctions:currentDevice type:3];
        
        AirConditionerFuncs *temp = [[MDXPGApplianceApi getInstance] getFunctions:currentDevice];
        
        NSLog(@"------ Minus 2 device type: %@", @([temp getDeviceType]));
        
        if ([baseMessage getCode] == 0)
        {
            self.labelResult.text = @"查询设备状态成功";
            
            NSLog(@"device status: %@", [status description]);
            
            NSLog(@"air condition funcs: %@", [funcs description]);
            
            _status = status;
            _funcs = funcs;
            
            /**
             *  AirConditionerFuncs 的各个成员变量的说明，请参照 readme.html 的说明
             */
            [self updateUIWithStatus:status];
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"查询设备状态失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 查询内风机时间
- (IBAction)actionQueryTime:(id)sender
{
    // 发送命令
    self.labelResult.text = @"正在查询内风机时间...";
    
    // 获取设备ID
    NSString *applianceID = [MDUserDefaults sharedInstance].currentApplianceID;
    
    [[MDXPGApplianceApi getInstance] queryFansRuntime:applianceID completion:^(BaseMessage *baseMessage, int time) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelResult.text = [NSString stringWithFormat:@"查询内风机时间成功，时间：%d", time];
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"查询内风机时间失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// B5查询
- (IBAction)actionB5Query:(id)sender
{
    // 发送命令
    self.labelResult.text = @"正在B5查询...";
    
    // 获取设备ID
    NSString *applianceID = [MDUserDefaults sharedInstance].currentApplianceID;
    
    [[MDXPGApplianceApi getInstance] queryB5:applianceID completion:^(BaseMessage *baseMessage, AirConditionerFuncs *funcs) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelResult.text = [NSString stringWithFormat:@"B5查询成功，功能状态：%@", [funcs description]];
            
            /**
             *  AirConditionerFuncs 的各个成员变量的说明，请参照 readme.html 的说明
             */
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"B5查询失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

// 清除电量数据
- (IBAction)actionClearPower:(id)sender
{
    // 发送命令
    self.labelResult.text = @"正在清除电量数据...";
    
    // 获取设备ID
    NSString *applianceID = [MDUserDefaults sharedInstance].currentApplianceID;
    
    [[MDXPGApplianceApi getInstance] clearPowerCal:applianceID completion:^(BaseMessage *baseMessage) {
        
        if ([baseMessage getCode] == 0)
        {
            self.labelResult.text = [NSString stringWithFormat:@"清除电量数据成功"];
            
            /**
             *  AirConditionerFuncs 的各个成员变量的说明，请参照 readme.html 的说明
             */
        }
        else
        {
            self.labelResult.text = [NSString stringWithFormat:@"清除电量数据失败. [%d]:%@", [baseMessage getCode], [baseMessage getMessage]];
        }
    }];
}

- (void)updateUIWithStatus:(DeviceStatus *)status
{
    self.textFieldTemperature.text = [NSString stringWithFormat:@"%d", status->setTemperature_];
    self.segmentedTempUnit.selectedSegmentIndex = status->tempUnit_;
    self.switchUpDown.on = status->updownFan_;
    self.switchLeftRight.on = status->leftRightFan_;
    
    switch (status->fanSpeed_)
    {
        case 102:
            self.segmentedSpeed.selectedSegmentIndex = 5;
            break;
            
        case 20:
            self.segmentedSpeed.selectedSegmentIndex = 0;
            break;
            
        case 40:
            self.segmentedSpeed.selectedSegmentIndex = 1;
            break;
            
        case 60:
            self.segmentedSpeed.selectedSegmentIndex = 2;
            break;
            
        case 80:
            self.segmentedSpeed.selectedSegmentIndex = 3;
            break;
            
        case 101:
            self.segmentedSpeed.selectedSegmentIndex = 4;
            break;
            
        default:
            break;
    }
    
    self.segmentedMode.selectedSegmentIndex = status->mode_ - 1;
    
    self.switchStrong.on = status->tubro_;
    self.switchECO.on = (int)status->eco_;
    self.switch8Hot.on = status->Eight_Hot_;
    
    if (status->mode_ == IDataBodyDevStauts_get_MODE_COLD() || (status->mode_ == IDataBodyDevStauts_get_MODE_HEAT() && _funcs->strongHot_))
    {
        
    }
    
    if ((status->mode_ == IDataBodyDevStauts_get_MODE_COLD() && _funcs->strongCool_) || (status->mode_ == IDataBodyDevStauts_get_MODE_HEAT() && _funcs->strongHot_))
    {
        
    }
}

@end
